package com.huqing.icu.base.redis.client;

import com.huqing.icu.base.redis.config.RedisClientConfig;
import com.huqing.icu.base.redis.config.RedisDeployType;
import com.huqing.icu.exceptions.UnexpectedException;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 单机Redis池
 * @Author huqing
 * @Date 2025/1/6 10:12
 **/
@Component
public class SingleRedisPool {

    @Autowired
    private RedisClientConfig redisClientConfig;

    private Map<String, JedisPool> pools = new HashMap<String, JedisPool>();

    //singleton pattern
    private SingleRedisPool() {
    }

    @Bean
    public JedisPool getJedisPool() {
        if (RedisDeployType.SINGLE.getCode().equals(redisClientConfig.getUsed())) {
            String[] addrs = redisClientConfig.getSingleAddr().split(",");
            if (ArrayUtils.isEmpty(addrs))
                throw new UnexpectedException("redis addr is empty");

            String addr = addrs[0];
            String ip = addr.split(":")[0];
            Integer port = Integer.valueOf(addr.split(":")[1]);
            JedisPool jedisPool = getJedisPool(ip, port);
            return jedisPool;
        }
        //不反悔null的原因是：部署xxl-job的时候，这里bean是null,导致xxl-job注入的失败失败
        //return null;
        return new JedisPool();
    }

    private JedisPool getJedisPool(String host, int port) {
        final String hostAndPort = host + ":" + port;
        JedisPool pool = null;
        if (pools.containsKey(hostAndPort)) {
            pool = pools.get(hostAndPort);
        } else {
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxTotal(redisClientConfig.getMaxTotal());
            jedisPoolConfig.setMaxIdle(redisClientConfig.getMaxIdLe());
            jedisPoolConfig.setMaxWaitMillis(redisClientConfig.getMaxWaitMillis());
            jedisPoolConfig.setTestOnBorrow(redisClientConfig.isTestOnBorrow());
            jedisPoolConfig.setTestOnReturn(redisClientConfig.isTestOnReturn());
            jedisPoolConfig.setMinIdle(redisClientConfig.getMinIdLe());
            pool = new JedisPool(jedisPoolConfig, host, port);
            pools.put(hostAndPort, pool);
        }
        return pool;
    }
}
